package com.example.act6.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {
    public static <T> T copyProperties(Object obj, Class<T> clazz) {
        try {
            T result = clazz.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(obj, result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Map<String, Object> copyNotBlankPropertiesToMap(Object o) {
        if (o == null) {
            return new HashMap<>();
        }

        Class c = o.getClass();
        Map<String, Object> map = new HashMap<>();
        try {
            Field[] fs = c.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                Object obj = f.get(o);
                if (null != obj) {
                    map.put(f.getName(), obj);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
